<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>

<%@ page import="com.conversationboard.model.*"%>
<%@ page import="com.conversationboard.view.*"%>
<%@ page import="java.security.Principal"%>
<%@ page import="com.conversationboard.config.*"%>
<%@ page import="com.conversationboard.site.*"%>
<%@ page import="com.conversationboard.authenticator.AuthenticationCookie"%>
<%@ page import="com.conversationboard.tree.Folders"%>
<%@ page import="com.conversationboard.tree.Node"%>
<%@ page import="java.util.List"%>
<%@ page import="com.conversationboard.controller.ipaddress.IPAddress"%>
<%@ page import="java.util.regex.Pattern"%>
<%@ page import="java.util.regex.Matcher"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="java.io.File"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.UUID"%>
<%@ page import="org.apache.commons.fileupload.FileUploadException"%>
<%@ page import="com.conversationboard.upload.IllegalFileChecker"%>
<%@ page import="com.conversationboard.filedownload.FileExtension"%>

<% 

	Pattern fileExtensionPattern = Pattern.compile("^.*?(\\..*)$", (Pattern.DOTALL | Pattern.CASE_INSENSITIVE));
	
	try {
		
		String boardId = request.getParameter("boardid");

		/* If we don't support file uploads, return */
	
		if (!Configuration.getInstance().isSupportFileUploads()) {
			return;
		}
		
		User user = User.get(request.getUserPrincipal().getName());
	
		/* Get the file and store it on disk */
	
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	
		if (!isMultipart) {
			return;
		}
	
		DiskFileItemFactory factory = new DiskFileItemFactory();
	
		String directoryName = Configuration.getInstance().getFileUploadRepository();
	
		/* If the directory name isn't set, then bale out */
	
		if ((directoryName == null) || (directoryName.trim().length() == 0)) {
			return;
		}
	
		File repositoryDirectory = new File(directoryName);
	
		/* If the repository directory doesn't exist, and the file isn't set to nothing, create it */
	
		if (!repositoryDirectory.exists()) {
			repositoryDirectory.mkdir();
		}
	
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(1000000000);
		List<FileItem> items = upload.parseRequest(request);
	
		/* Think the files are actually there now... Print out their names */

		String url = "";
		request.setAttribute("illegalFile", false);
		
		for (FileItem item : items) {
	
			if (!item.isFormField()) {

				String fileName = item.getName();
				
				/* The following two lines shouldn't be necessary, but on Windows, the above line doesn't strip out the path properly */
				
				File fileObject = new File(fileName);
				fileName = fileObject.getName();
				
				String extension = FileExtension.get(fileName);
				boolean isImage = Images.isImageFileExtension(extension);

				/* Reject any attempts to subvert the Tomcat container - these won't work as they'll go in the wrong
				   place anyway, but worth preventing at all. */
				
				if (IllegalFileChecker.isIllegalFile(fileName)) {
					request.setAttribute("illegalFile", true);
					break;
				}
				
				if ((!isImage) && (Configuration.getInstance().isOnlySupportImageUploads())) {
					request.setAttribute("illegalFile", true);
					break;
				}
				
				/* Generate a new file name: board ID tacked on to a GUID */
	
				String uniqueFileId = boardId + "-" + UUID.randomUUID().toString();
	
				/* Get the file's extension, if it has one, because we want to keep it the same as it was */
	
				File newFile = new File(directoryName + "/" + uniqueFileId);
	
				/* Write the file into the specified directory */
	
				item.write(newFile);
	
				/* Now associate this file with the original file name, the user, and a timestamp */
	
				UploadedFile file = FileUpload.store(user, fileName, item.getSize(), uniqueFileId, isImage);
				
				url = file.getBBCode();
	
				user.addUploadedFile(file);
			}
		}
		
		request.setAttribute("url", url);
	
	} catch (FileUploadException e) {
		throw new ServletException(e);
	} catch (Exception e) {
		throw new ServletException(e);
	}

%>





<%@page import="com.conversationboard.logger.Logger"%>
<%@page import="java.util.Date"%><html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="ROBOTS" content="NOINDEX"></meta>
<title>File Successfully Uploaded</title>
<link rel="stylesheet" title="Conversation Board" type="text/css" href="${contextPath}/Stylesheets/<%=StyleSheets.getStyleSheetFileName(request.getCookies())%>">
</head>

<body>

<div class="headingblock"><c:choose>
	<c:when test="${illegalFile}">
		<h1>Error Uploading File</h1>
	</c:when>
	<c:otherwise>
		<h1>File Successfully Uploaded</h1>
	</c:otherwise>
</c:choose></div>

<div class="mainblock">

<div class="formsection"><c:choose>
	<c:when test="${illegalFile}">
		<p class="red"><strong>You cannot upload JSPs, class files or web deployment descriptors. If the site is configured to only allow image uploads, then you will
		                       not be allowed to upload any other types of file.</strong></p>
	</c:when>
	<c:otherwise>
		<p>To link to this file, or to paste an image, please copy and paste the following into your post or thread:</p>

		<div class="formsection">${url}</div>

		<br />
		<br />

		<input type="button" value="Close Window" onclick="window.close();">
	</c:otherwise>
</c:choose></div>

</div>

<!--<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>-->
<!--<script type="text/javascript">_uacct = "UA-1148679-1";urchinTracker();</script>-->

</body>
</html>
